use ggez::event::{self, EventHandler};
use ggez::graphics::{self, Color, DrawParam, PxScale, Rect, TextFragment};
use ggez::input::keyboard::KeyCode;
use ggez::{Context, ContextBuilder, GameResult};
use rand::seq::SliceRandom;

const PLAYER_SIZE: f32 = 30.0;
const MOTHER_SIZE: f32 = 40.0;
const PLAYER_SPEED: f32 = 5.0;
const BASE_MOTHER_SPEED: f32 = 3.0;
const MOTHER_SPEED_INCREMENT: f32 = 0.1; // 每100分增加的速度
const MOTHER_VISION_RANGE: f32 = 150.0; // 妈妈的视野范围
const MOTHER_CORRIDOR_VISION_RANGE: f32 = 250.0; // 妈妈在走廊时的视野范围
const SCREEN_WIDTH: f32 = 1000.0;
const SCREEN_HEIGHT: f32 = 600.0;
const ROOM_SIZE: f32 = 250.0;
const ROOM_GAP: f32 = 100.0;
const CORRIDOR_WIDTH: f32 = 80.0;
const MOTHER_ROOM_CHANGE_TIME: f32 = 5.0;
const DOOR_WIDTH: f32 = 60.0;
const DOOR_HEIGHT: f32 = 10.0;
const TV_SIZE: f32 = 40.0;
const TV_RANGE: f32 = 100.0;
const FATIGUE_INCREASE_RATE: f32 = 0.1; // 看电视时疲劳值增加速度
const FATIGUE_RECOVERY_RATE: f32 = 0.2; // 在卧室休息时疲劳值恢复速度
const MAX_FATIGUE: f32 = 100.0; // 最大疲劳值

#[derive(PartialEq, Copy, Clone)]
enum Room {
    LivingRoom,
    StudyRoom,
    Kitchen,
    Bedroom,
}

struct MainState {
    player_pos: [f32; 2],
    mother_pos: [f32; 2],
    mother_direction: [f32; 2],
    score: i32,
    game_over: bool,
    studying_mode: bool,
    current_room: Room,
    mother_target_room: Room,
    mother_room_timer: f32,
    tv_pos: [f32; 2],
    fatigue: f32,
    mother_spotted_player: bool,
    game_started: bool,
    mother_rage: bool,      // 新增：妈妈的暴怒状态
    mother_rage_timer: f32, // 新增：暴怒状态计时器
}

impl MainState {
    fn new(_ctx: &mut Context) -> GameResult<MainState> {
        let all_rooms = [
            Room::LivingRoom,
            Room::StudyRoom,
            Room::Kitchen,
            Room::Bedroom,
        ];
        let initial_room = *all_rooms.choose(&mut rand::thread_rng()).unwrap();
        let living_room = Rect::new(0.0, 0.0, ROOM_SIZE, ROOM_SIZE);

        Ok(MainState {
            player_pos: [SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0],
            mother_pos: [0.0, 0.0],
            mother_direction: [1.0, 0.0],
            score: 0,
            game_over: false,
            studying_mode: false,
            current_room: Room::LivingRoom,
            mother_target_room: initial_room,
            mother_room_timer: MOTHER_ROOM_CHANGE_TIME,
            tv_pos: [
                living_room.x + living_room.w / 2.0,
                living_room.y + living_room.h / 2.0,
            ],
            fatigue: 0.0,
            mother_spotted_player: false,
            game_started: false,
            mother_rage: false,
            mother_rage_timer: 0.0,
        })
    }

    // 新增：获取房间位置
    fn get_room_rect(&self, room: Room) -> Rect {
        match room {
            Room::LivingRoom => Rect::new(0.0, 0.0, ROOM_SIZE, ROOM_SIZE),
            Room::StudyRoom => Rect::new(0.0, ROOM_SIZE + ROOM_GAP, ROOM_SIZE, ROOM_SIZE),
            Room::Kitchen => Rect::new(SCREEN_WIDTH - ROOM_SIZE, 0.0, ROOM_SIZE, ROOM_SIZE),
            Room::Bedroom => Rect::new(
                SCREEN_WIDTH - ROOM_SIZE,
                ROOM_SIZE + ROOM_GAP,
                ROOM_SIZE,
                ROOM_SIZE,
            ),
        }
    }

    fn get_corridor_rect(&self) -> Rect {
        Rect::new(
            ROOM_SIZE,
            0.0,
            SCREEN_WIDTH - 2.0 * ROOM_SIZE,
            SCREEN_HEIGHT,
        )
    }

    fn get_room_doors(&self, room: Room) -> Vec<Rect> {
        let mut doors = Vec::new();
        let room_rect = self.get_room_rect(room);

        match room {
            Room::LivingRoom => {
                // 右门
                doors.push(Rect::new(
                    room_rect.x + room_rect.w - DOOR_HEIGHT / 2.0,
                    room_rect.y + room_rect.h / 2.0 - DOOR_WIDTH / 2.0,
                    DOOR_HEIGHT,
                    DOOR_WIDTH,
                ));
            }
            Room::StudyRoom => {
                // 右门
                doors.push(Rect::new(
                    room_rect.x + room_rect.w - DOOR_HEIGHT / 2.0,
                    room_rect.y + room_rect.h / 2.0 - DOOR_WIDTH / 2.0,
                    DOOR_HEIGHT,
                    DOOR_WIDTH,
                ));
            }
            Room::Kitchen => {
                // 左门
                doors.push(Rect::new(
                    room_rect.x - DOOR_HEIGHT / 2.0,
                    room_rect.y + room_rect.h / 2.0 - DOOR_WIDTH / 2.0,
                    DOOR_HEIGHT,
                    DOOR_WIDTH,
                ));
            }
            Room::Bedroom => {
                // 左门
                doors.push(Rect::new(
                    room_rect.x - DOOR_HEIGHT / 2.0,
                    room_rect.y + room_rect.h / 2.0 - DOOR_WIDTH / 2.0,
                    DOOR_HEIGHT,
                    DOOR_WIDTH,
                ));
            }
        }
        doors
    }

    fn is_valid_move(&self, new_pos: [f32; 2]) -> bool {
        // 检查是否在走廊内
        let corridor = self.get_corridor_rect();
        if corridor.contains(new_pos) {
            return true;
        }

        // 检查是否在任何门的范围内
        for room in [
            Room::LivingRoom,
            Room::StudyRoom,
            Room::Kitchen,
            Room::Bedroom,
        ]
        .iter()
        {
            for door in self.get_room_doors(*room) {
                if door.contains(new_pos) {
                    return true;
                }
            }
        }

        // 检查是否在任何房间内
        for room in [
            Room::LivingRoom,
            Room::StudyRoom,
            Room::Kitchen,
            Room::Bedroom,
        ]
        .iter()
        {
            let rect = self.get_room_rect(*room);
            if rect.contains(new_pos) {
                return true;
            }
        }

        false
    }

    // 新增：检查玩家在哪个房间
    fn update_current_room(&mut self) {
        for room in [
            Room::LivingRoom,
            Room::StudyRoom,
            Room::Kitchen,
            Room::Bedroom,
        ]
        .iter()
        {
            let rect = self.get_room_rect(*room);
            if rect.contains([self.player_pos[0], self.player_pos[1]]) {
                self.current_room = *room;
                break;
            }
        }
    }

    fn update_mother_target(&mut self) {
        let all_rooms = [
            Room::LivingRoom,
            Room::StudyRoom,
            Room::Kitchen,
            Room::Bedroom,
        ];
        let available_rooms: Vec<Room> = all_rooms
            .iter()
            .filter(|&&r| r != self.mother_target_room)
            .cloned()
            .collect();
        if let Some(new_room) = available_rooms.choose(&mut rand::thread_rng()) {
            self.mother_target_room = *new_room;
        }
    }

    fn is_in_tv_range(&self) -> bool {
        let dx = self.player_pos[0] - self.tv_pos[0];
        let dy = self.player_pos[1] - self.tv_pos[1];
        let distance = (dx * dx + dy * dy).sqrt();
        distance <= TV_RANGE
    }
}

impl EventHandler for MainState {
    fn update(&mut self, _ctx: &mut Context) -> GameResult {
        let kb = &_ctx.keyboard;

        if !self.game_started {
            if kb.is_key_pressed(KeyCode::Return) {
                self.game_started = true;
            }
            return Ok(());
        }

        if self.game_over {
            if kb.is_key_pressed(KeyCode::Return) {
                // 重置游戏状态
                self.player_pos = [SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 2.0];
                self.mother_pos = [0.0, 0.0];
                self.mother_direction = [1.0, 0.0];
                self.score = 0;
                self.game_over = false;
                self.studying_mode = false;
                self.current_room = Room::LivingRoom;
                self.mother_target_room = *[
                    Room::LivingRoom,
                    Room::StudyRoom,
                    Room::Kitchen,
                    Room::Bedroom,
                ]
                .choose(&mut rand::thread_rng())
                .unwrap();
                self.mother_room_timer = MOTHER_ROOM_CHANGE_TIME;
                self.fatigue = 0.0;
                self.mother_spotted_player = false;
            }
            return Ok(());
        }

        let mut new_pos = self.player_pos;

        if kb.is_key_pressed(KeyCode::Left) {
            new_pos[0] = (new_pos[0] - PLAYER_SPEED).max(0.0);
        }
        if kb.is_key_pressed(KeyCode::Right) {
            new_pos[0] = (new_pos[0] + PLAYER_SPEED).min(SCREEN_WIDTH);
        }
        if kb.is_key_pressed(KeyCode::Up) {
            new_pos[1] = (new_pos[1] - PLAYER_SPEED).max(0.0);
        }
        if kb.is_key_pressed(KeyCode::Down) {
            new_pos[1] = (new_pos[1] + PLAYER_SPEED).min(SCREEN_HEIGHT);
        }

        // 只有当新位置有效时才更新玩家位置
        if self.is_valid_move(new_pos) {
            self.player_pos = new_pos;
        }

        // 更新玩家位置后，更新当前房间
        self.update_current_room();

        // 根据房间限制模式切换
        if kb.is_key_pressed(KeyCode::Space) {
            match self.current_room {
                Room::LivingRoom => {
                    // 只能在客厅的电视机范围内关闭学习模式（开始看电视）
                    if self.studying_mode && self.is_in_tv_range() {
                        self.studying_mode = false;
                    }
                }
                Room::StudyRoom => {
                    // 只能在书房开启学习模式
                    if !self.studying_mode {
                        self.studying_mode = true;
                    }
                }
                _ => {} // 其他房间按空格无效
            }
        }

        // 只有在客厅的电视机范围内看电视才能得分
        if !self.studying_mode && self.current_room == Room::LivingRoom && self.is_in_tv_range() {
            self.score += 1;
        }

        // 更新疲劳值
        if !self.studying_mode && self.current_room == Room::LivingRoom && self.is_in_tv_range() {
            self.fatigue = (self.fatigue + FATIGUE_INCREASE_RATE).min(MAX_FATIGUE);
        } else if self.current_room == Room::Bedroom {
            self.fatigue = (self.fatigue - FATIGUE_RECOVERY_RATE).max(0.0);
        }

        // 检查妈妈是否能看到玩家
        let dx = self.player_pos[0] - self.mother_pos[0];
        let dy = self.player_pos[1] - self.mother_pos[1];
        let distance_to_player = (dx * dx + dy * dy).sqrt();
        let corridor = self.get_corridor_rect();
        let vision_range = if corridor.contains([self.mother_pos[0], self.mother_pos[1]]) {
            MOTHER_CORRIDOR_VISION_RANGE
        } else {
            MOTHER_VISION_RANGE
        };

        // 如果玩家在看电视或者在视野范围内，妈妈会发现玩家
        self.mother_spotted_player =
            (!self.studying_mode && self.current_room == Room::LivingRoom && self.is_in_tv_range())
                || distance_to_player <= vision_range;

        // 妈妈的行为逻辑
        if self.studying_mode {
            // 如果看到学习，随机选择去厨房或卧室
            let target_room = if rand::random::<bool>() {
                Room::Kitchen
            } else {
                Room::Bedroom
            };
            let target_rect = self.get_room_rect(target_room);
            let target_pos = [
                target_rect.x + target_rect.w / 2.0,
                target_rect.y + target_rect.h / 2.0,
            ];

            let dx = target_pos[0] - self.mother_pos[0];
            let dy = target_pos[1] - self.mother_pos[1];
            let distance = (dx * dx + dy * dy).sqrt();

            if distance > 0.0 {
                self.mother_direction[0] = dx / distance;
                self.mother_direction[1] = dy / distance;
            }
        } else if self.mother_spotted_player {
            // 如果发现玩家，直接追击
            if distance_to_player > 0.0 {
                self.mother_direction[0] = dx / distance_to_player;
                self.mother_direction[1] = dy / distance_to_player;
            }
        } else {
            // 正常巡逻
            let target_rect = self.get_room_rect(self.mother_target_room);
            let target_pos = [
                target_rect.x + target_rect.w / 2.0,
                target_rect.y + target_rect.h / 2.0,
            ];
            let dx = target_pos[0] - self.mother_pos[0];
            let dy = target_pos[1] - self.mother_pos[1];
            let distance = (dx * dx + dy * dy).sqrt();

            if distance > 0.0 {
                self.mother_direction[0] = dx / distance;
                self.mother_direction[1] = dy / distance;
            }
        }

        // 更新妈妈的房间计时器和目标房间
        self.mother_room_timer -= _ctx.time.delta().as_secs_f32();
        if self.mother_room_timer <= 0.0 {
            // 如果妈妈在书房且没有找到玩家，进入暴怒状态
            let mother_in_study = self
                .get_room_rect(Room::StudyRoom)
                .contains([self.mother_pos[0], self.mother_pos[1]]);
            if mother_in_study && !self.mother_spotted_player {
                self.mother_rage = true;
                self.mother_rage_timer = 5.0; // 暴怒持续5秒
            }
            self.update_mother_target();
            self.mother_room_timer = MOTHER_ROOM_CHANGE_TIME;
        }

        // 更新暴怒状态计时器
        if self.mother_rage {
            self.mother_rage_timer -= _ctx.time.delta().as_secs_f32();
            if self.mother_rage_timer <= 0.0 {
                self.mother_rage = false;
            }
        }

        // 获取目标房间的中心位置
        let target_rect = self.get_room_rect(self.mother_target_room);
        let target_pos = [
            target_rect.x + target_rect.w / 2.0,
            target_rect.y + target_rect.h / 2.0,
        ];

        // 计算妈妈到目标位置的方向
        let dx = target_pos[0] - self.mother_pos[0];
        let dy = target_pos[1] - self.mother_pos[1];
        let distance = (dx * dx + dy * dy).sqrt();

        if distance > 0.0 {
            self.mother_direction[0] = dx / distance;
            self.mother_direction[1] = dy / distance;
        }

        // 计算妈妈的实际速度（基础速度 + 根据分数增加的速度）
        let mother_speed = BASE_MOTHER_SPEED + (self.score as f32 / 100.0) * MOTHER_SPEED_INCREMENT;
        // 如果发现玩家或处于暴怒状态，速度增加
        let actual_speed = if self.mother_spotted_player {
            mother_speed * 1.5
        } else if self.mother_rage {
            mother_speed * 2.0 // 暴怒状态速度翻倍
        } else {
            mother_speed
        };

        // 更新妈妈位置
        self.mother_pos[0] += self.mother_direction[0] * actual_speed;
        self.mother_pos[1] += self.mother_direction[1] * actual_speed;

        // 确保妈妈不会超出屏幕范围
        self.mother_pos[0] = self.mother_pos[0].clamp(0.0, SCREEN_WIDTH);
        self.mother_pos[1] = self.mother_pos[1].clamp(0.0, SCREEN_HEIGHT);

        // 根据疲劳值调整玩家速度
        let fatigue_speed_multiplier = 1.0 - (self.fatigue / MAX_FATIGUE) * 0.5; // 最多减速50%
        let _actual_player_speed = PLAYER_SPEED * fatigue_speed_multiplier;

        // 检查玩家是否从客厅进入走廊
        let corridor = self.get_corridor_rect();
        let is_in_corridor = corridor.contains([self.player_pos[0], self.player_pos[1]]);
        if is_in_corridor && self.current_room == Room::LivingRoom && self.mother_spotted_player {
            // 如果玩家从客厅进入走廊且被发现，妈妈加速追赶
            let dx = self.player_pos[0] - self.mother_pos[0];
            let dy = self.player_pos[1] - self.mother_pos[1];
            let distance = (dx * dx + dy * dy).sqrt();
            if distance > 0.0 {
                self.mother_direction[0] = dx / distance;
                self.mother_direction[1] = dy / distance;
                // 妈妈速度增加100%
                let mother_speed = (BASE_MOTHER_SPEED
                    + (self.score as f32 / 100.0) * MOTHER_SPEED_INCREMENT)
                    * 2.0;
                self.mother_pos[0] += self.mother_direction[0] * mother_speed;
                self.mother_pos[1] += self.mother_direction[1] * mother_speed;
            }
        }

        // 检查玩家是否从书房出来
        if self.current_room != Room::StudyRoom && self.studying_mode {
            self.studying_mode = false;
            self.score += 100; // 奖励100分
        }

        // 检测碰撞
        let distance = ((self.player_pos[0] - self.mother_pos[0]).powi(2)
            + (self.player_pos[1] - self.mother_pos[1]).powi(2))
        .sqrt();

        if distance < PLAYER_SIZE + MOTHER_SIZE {
            if !self.studying_mode {
                self.game_over = true;
            }
        } else {
            if !self.studying_mode && self.current_room == Room::LivingRoom && self.is_in_tv_range()
            {
                self.score += 1;
            }
        }

        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        let mut canvas = graphics::Canvas::from_frame(ctx, Color::WHITE);

        if !self.game_started {
            // 绘制开始界面
            let title = graphics::Text::new(TextFragment {
                text: "Watch TV Game".to_string(),
                scale: Some(PxScale::from(30.0)),
                ..Default::default()
            });
            let instructions = graphics::Text::new(TextFragment {
                text: "Game Instructions(Created by daizixuan & daianzhen):\n\n
                You are a kid who wants to secretly watch TV, but beware of Mom's patrol!\n\n
                Controls:\n
                - Use arrow keys to move\n
                - Press Space in Living Room to watch TV and gain points\n
                - Press Space in Study Room to study and avoid being caught\n
                - Rest in Bedroom to recover from fatigue\n\n
                Scoring:\n
                - Gain 1 point per second while watching TV\n
                - Get 100 bonus points when leaving Study Room\n\n
                Mom's Behavior:\n
                - Will chase player when in sight\n
                - Enters Rage Mode if can't find player in Study Room\n
                - Moves twice as fast in Rage Mode\n\n
                Press Enter to Start
                "
                    .to_string(),
                scale: Some(PxScale::from(16.0)),
                ..Default::default()
            });

            canvas.draw(
                &title,
                DrawParam::default()
                    .dest([SCREEN_WIDTH / 2.0 - 150.0, SCREEN_HEIGHT / 4.0])
                    .scale([2.0, 2.0])
                    .color(Color::BLACK),
            );

            canvas.draw(
                &instructions,
                DrawParam::default()
                    .dest([SCREEN_WIDTH / 2.0 - 300.0, SCREEN_HEIGHT / 2.0])
                    .color(Color::BLACK),
            );

            canvas.finish(ctx)?;
            return Ok(());
        }

        // 绘制走廊
        let corridor = self.get_corridor_rect();
        canvas.draw(
            &graphics::Mesh::new_rectangle(
                ctx,
                graphics::DrawMode::fill(),
                corridor,
                Color::new(0.85, 0.85, 0.85, 1.0), // 浅灰色
            )?,
            DrawParam::default(),
        );

        // 绘制房间
        for room in [
            Room::LivingRoom,
            Room::StudyRoom,
            Room::Kitchen,
            Room::Bedroom,
        ]
        .iter()
        {
            let rect = self.get_room_rect(*room);
            let (room_color, room_name) = match room {
                Room::LivingRoom => (Color::new(0.9, 0.9, 0.8, 1.0), "Living Room"),
                Room::StudyRoom => (Color::new(0.8, 0.9, 1.0, 1.0), "Study Room"),
                Room::Kitchen => (Color::new(1.0, 0.9, 0.8, 1.0), "Kitchen"),
                Room::Bedroom => (Color::new(0.9, 0.8, 1.0, 1.0), "Bedroom"),
            };

            // 绘制房间底色
            canvas.draw(
                &graphics::Mesh::new_rectangle(ctx, graphics::DrawMode::fill(), rect, room_color)?,
                DrawParam::default(),
            );

            // 绘制房间边框（墙壁）
            canvas.draw(
                &graphics::Mesh::new_rectangle(
                    ctx,
                    graphics::DrawMode::stroke(4.0),
                    rect,
                    Color::new(0.4, 0.4, 0.4, 1.0), // 深灰色墙壁
                )?,
                DrawParam::default(),
            );

            // 绘制门
            for door in self.get_room_doors(*room) {
                // 绘制门的底色
                canvas.draw(
                    &graphics::Mesh::new_rectangle(
                        ctx,
                        graphics::DrawMode::fill(),
                        door,
                        Color::new(0.8, 0.6, 0.4, 1.0), // 浅棕色
                    )?,
                    DrawParam::default(),
                );

                // 绘制门的边框
                canvas.draw(
                    &graphics::Mesh::new_rectangle(
                        ctx,
                        graphics::DrawMode::stroke(2.0),
                        door,
                        Color::new(0.6, 0.4, 0.2, 1.0), // 深棕色
                    )?,
                    DrawParam::default(),
                );

                // 绘制门把手
                let handle_size = 4.0;
                let handle_pos = if door.w > door.h {
                    // 水平门
                    [
                        door.x + door.w - 10.0,
                        door.y + door.h / 2.0 - handle_size / 2.0,
                    ]
                } else {
                    // 垂直门
                    [
                        door.x + door.w / 2.0 - handle_size / 2.0,
                        door.y + door.h - 10.0,
                    ]
                };

                canvas.draw(
                    &graphics::Mesh::new_circle(
                        ctx,
                        graphics::DrawMode::fill(),
                        [handle_pos[0], handle_pos[1]],
                        handle_size,
                        0.1,
                        Color::new(0.3, 0.2, 0.1, 1.0), // 深褐色
                    )?,
                    DrawParam::default(),
                );
            }

            // 绘制房间名称和提示
            let mut text = room_name.to_string();
            if *room == Room::LivingRoom {
                text.push_str("\n(Space to watch TV)");
            } else if *room == Room::StudyRoom {
                text.push_str("\n(Space to study)");
            }

            let room_text = graphics::Text::new(TextFragment {
                text: text,
                scale: Some(PxScale::from(14.0)),
                ..Default::default()
            });
            canvas.draw(
                &room_text,
                DrawParam::default()
                    .dest([rect.x + 10.0, rect.y + 10.0])
                    .color(Color::BLACK),
            );
        }

        // 绘制玩家
        let player_color = if self.studying_mode {
            Color::GREEN
        } else {
            Color::BLUE
        };

        canvas.draw(
            &graphics::Mesh::new_rectangle(
                ctx,
                graphics::DrawMode::fill(),
                Rect::new(
                    self.player_pos[0] - PLAYER_SIZE / 2.0,
                    self.player_pos[1] - PLAYER_SIZE / 2.0,
                    PLAYER_SIZE,
                    PLAYER_SIZE,
                ),
                player_color,
            )?,
            DrawParam::default(),
        );

        // 绘制妈妈
        let mother_color = if self.mother_rage {
            Color::RED
        } else if self.mother_spotted_player {
            Color::YELLOW
        } else {
            Color::MAGENTA
        };
        canvas.draw(
            &graphics::Mesh::new_circle(
                ctx,
                graphics::DrawMode::fill(),
                [self.mother_pos[0], self.mother_pos[1]],
                MOTHER_SIZE,
                0.1,
                mother_color,
            )?,
            DrawParam::default(),
        );

        // 绘制分数和疲劳值
        let score_text = graphics::Text::new(TextFragment {
            text: format!("Score: {}", self.score),
            scale: Some(PxScale::from(16.0)),
            ..Default::default()
        });
        let fatigue_text = graphics::Text::new(TextFragment {
            text: format!("Fatigue: {:.0}%", self.fatigue),
            scale: Some(PxScale::from(16.0)),
            ..Default::default()
        });
        canvas.draw(
            &score_text,
            DrawParam::default()
                .dest([SCREEN_WIDTH - 100.0, 10.0])
                .color(Color::BLACK),
        );
        canvas.draw(
            &fatigue_text,
            DrawParam::default()
                .dest([SCREEN_WIDTH - 100.0, 30.0])
                .color(Color::BLACK),
        );

        // 如果妈妈发现了玩家，绘制警告标志
        if self.mother_spotted_player {
            let warning_text = graphics::Text::new(TextFragment {
                text: "Warning: Mom spotted you!".to_string(),
                scale: Some(PxScale::from(20.0)),
                ..Default::default()
            });
            canvas.draw(
                &warning_text,
                DrawParam::default()
                    .dest([SCREEN_WIDTH / 2.0 - 100.0, 10.0])
                    .color(Color::RED),
            );
        }

        if self.game_over {
            let game_over_text = graphics::Text::new(TextFragment {
                text: format!(
                    "Game Over! Final Score: {}\n\nPress Enter to Restart",
                    self.score
                ),
                scale: Some(PxScale::from(30.0)),
                ..Default::default()
            });
            canvas.draw(
                &game_over_text,
                DrawParam::default()
                    .dest([SCREEN_WIDTH / 2.0 - 100.0, SCREEN_HEIGHT / 2.0])
                    .color(Color::RED),
            );
        }

        canvas.finish(ctx)?;
        Ok(())
    }

    // 移除原有的 key_down_event 函数，因为空格键逻辑已经移到 update 中
}

fn main() -> GameResult {
    let (mut ctx, event_loop) = ContextBuilder::new("watch_tv", "trae")
        .window_setup(ggez::conf::WindowSetup::default().title("Watch TV Game"))
        .window_mode(ggez::conf::WindowMode::default().dimensions(SCREEN_WIDTH, SCREEN_HEIGHT))
        .build()?;

    let state = MainState::new(&mut ctx)?;
    event::run(ctx, event_loop, state)
}
